'use client'

import { useState, useEffect, useRef } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend, PieChart, Pie, Cell } from 'recharts'
import { createClient } from '@/lib/supabase/client'
import { EmotionAnalyzer } from '@/lib/agents/emotion-analyzer'
import { UserContext } from '@/lib/types/agent'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Database } from '@/lib/supabase/types'
import { useToast } from '@/components/ui/use-toast'

type EmotionTracking = Database['public']['Tables']['emotion_tracking']['Row']

export function EmotionalHealthOverview({ userId }: { userId: string }) {
  const [emotionData, setEmotionData] = useState<EmotionTracking[]>([])
  const [loading, setLoading] = useState(true)
  const [analyzing, setAnalyzing] = useState(false)
  const [userInput, setUserInput] = useState('')
  const [analysisResult, setAnalysisResult] = useState<string | null>(null)
  const supabase = createClient()
  const toast = useToast();
  const emotionAnalyzerRef = useRef<EmotionAnalyzer | null>(null)

  // 初始化情绪分析器
  useEffect(() => {
    emotionAnalyzerRef.current = new EmotionAnalyzer()
  }, [])

  // 获取情绪数据
  useEffect(() => {
    const fetchEmotionData = async () => {
      try {
        setLoading(true)
        const { data, error } = await supabase
          .from('emotion_tracking')
          .select('*')
          .eq('user_id', userId)
          .order('recorded_at', { ascending: false })
          .limit(30)

        if (error) throw error

        setEmotionData(data || [])
      } catch (error) {
        console.error('Error fetching emotion data:', error)
        toast({ title: 'Failed to load emotion data', status: 'error' })
      } finally {
        setLoading(false)
      }
    }

    fetchEmotionData()
  }, [userId, toast])

  // 分析用户输入的情绪
  const analyzeUserInput = async () => {
    if (!userInput.trim() || !emotionAnalyzerRef.current) return

    setAnalyzing(true)
    setAnalysisResult(null)

    try {
      // 准备用户上下文
      const userContext: UserContext = {
        userId,
        sessionId: 'temp-session-id', // 临时会话ID
        emotionalHistory: emotionData.map(item => ({
            primaryEmotion: item.primary_emotion,
            intensity: item.emotion_intensity,
            timestamp: item.recorded_at,
            valence: 0, // 默认为0
            arousal: 0, // 默认为0
            confidence: 0, // 默认为0
            emotions: {
              joy: 0,
              sadness: 0,
              anger: 0,
              fear: 0,
              surprise: 0,
              disgust: 0,
              anxiety: 0,
              depression: 0
            },
            linguisticMarkers: [],
            emotionalTrend: 'stable'
          })),
        recentMemories: [],
        activeGoals: [],
        crisisHistory: []
      }

      // 调用情绪分析器
      const result = await emotionAnalyzerRef.current.analyzeEmotion(
        userInput,
        userContext,
        'standard'
      )

      // 保存分析结果到数据库
      const emotionVectorMatch = result.metadata?.reasoning?.match(/- Valence: ([\d.]+), Arousal: ([\d.]+)/) ?? null
      const emotionVector = emotionVectorMatch
        ? [parseFloat(emotionVectorMatch[1]), parseFloat(emotionVectorMatch[2])]
        : [0, 0]

      const primaryEmotionMatch = result.metadata?.reasoning?.match(/Primary: ([\w ]+)/) ?? null
      const primaryEmotion = primaryEmotionMatch ? primaryEmotionMatch[1] : 'Neutral'

      await supabase.from('emotion_tracking').insert({
        user_id: userId,
        primary_emotion: primaryEmotion,
        emotion_intensity: Math.round(result.confidence * 10),
        emotion_vector: emotionVector,
        confidence_score: result.confidence,
        triggers: [userInput.substring(0, 50)],
        detection_method: 'emotion_analyzer',
        recorded_at: new Date().toISOString()
      })

      // 更新UI
      setAnalysisResult(result.content)
      toast({ title: 'Emotion analyzed successfully', status: 'success' })

      // 重新获取情绪数据
      await fetchEmotionData()
    } catch (error) {
      console.error('Error analyzing emotion:', error)
      toast({ title: 'Failed to analyze emotion', status: 'error' })
    } finally {
      setAnalyzing(false)
      setUserInput('')
    }
  }

  // 格式化情绪数据用于图表展示
  const chartData = emotionData
    .sort((a, b) => new Date(a.recorded_at).getTime() - new Date(b.recorded_at).getTime())
    .map(item => ({
      date: new Date(item.recorded_at).toLocaleDateString(),
      [item.primary_emotion]: item.emotion_intensity
    }))

  // 情绪分布数据
  const emotionDistribution = emotionData.reduce((acc, item) => {
    acc[item.primary_emotion] = (acc[item.primary_emotion] || 0) + 1
    return acc
  }, {} as Record<string, number>)

  const distributionData = Object.entries(emotionDistribution).map(([name, value]) => ({
    name,
    value
  }))

  // 情绪颜色映射
  const COLORS = ['#86EFAC', '#93C5FD', '#FCA5A5', '#FB923C', '#A5B4FC', '#FCD34D']

  // 重新获取情绪数据函数
  const fetchEmotionData = async () => {
    try {
      const { data, error } = await supabase
        .from('emotion_tracking')
        .select('*')
        .eq('user_id', userId)
        .order('recorded_at', { ascending: false })
        .limit(30)

      if (error) throw error

      setEmotionData(data || [])
    } catch (error) {
      console.error('Error fetching emotion data:', error)
    }
  }

  if (loading) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>Emotional Health Overview</CardTitle>
          <CardDescription>
            Track and analyze your emotional patterns over time
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="h-96 flex items-center justify-center text-gray-500">
            <div className="text-center">
              <div className="text-lg font-medium">Loading emotion data...</div>
            </div>
          </div>
        </CardContent>
      </Card>
    )
  }

  return (
    <Card className="h-full">
      <CardHeader>
        <CardTitle>Emotional Health Overview</CardTitle>
        <CardDescription>
          Track and analyze your emotional patterns over time
        </CardDescription>
      </CardHeader>
      <CardContent className="h-full flex flex-col">
        {/* 情绪分析输入区域 */}
        <div className="mb-8 p-4 bg-gray-50 rounded-lg border border-gray-100">
          <h3 className="text-lg font-medium mb-3">Analyze Your Emotion</h3>
          <div className="flex flex-col md:flex-row gap-3">
            <Input
              type="text"
              placeholder="How are you feeling today? Describe your emotions..."
              value={userInput}
              onChange={(e) => setUserInput(e.target.value)}
              className="flex-grow"
              disabled={analyzing}
            />
            <Button
              onClick={analyzeUserInput}
              disabled={analyzing || !userInput.trim()}
              loading={analyzing}
            >
              Analyze
            </Button>
          </div>

          {analysisResult && (
            <div className="mt-4 p-3 bg-green-50 border border-green-100 rounded-md">
              <h4 className="font-medium text-green-800">Analysis Result:</h4>
              <p className="text-green-700 mt-1">{analysisResult}</p>
            </div>
          )}
        </div>

        {/* 情绪图表区域 */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 flex-grow">
          {/* 情绪趋势图表 */}
          <div className="bg-white p-4 rounded-lg border border-gray-100 h-64">
            <h3 className="text-md font-medium mb-3">Emotional Trends</h3>
            <ResponsiveContainer width="100%" height="85%">
              <LineChart
                data={chartData}
                margin={{ top: 5, right: 20, left: 0, bottom: 5 }}
              >
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="date" tick={{ fontSize: 12 }} />
                <YAxis domain={[0, 10]} label={{ value: 'Intensity', angle: -90, position: 'insideLeft', fontSize: 12 }} />
                <Tooltip />
                <Legend verticalAlign="top" height={36} />
                {Object.keys(emotionDistribution).map((emotion, index) => (
                  <Line
                    key={emotion}
                    type="monotone"
                    dataKey={emotion}
                    stroke={COLORS[index % COLORS.length]}
                    activeDot={{ r: 8 }}
                    name={emotion}
                  />
                ))}
              </LineChart>
            </ResponsiveContainer>
          </div>

          {/* 情绪分布饼图 */}
          <div className="bg-white p-4 rounded-lg border border-gray-100 h-64">
            <h3 className="text-md font-medium mb-3">Emotion Distribution</h3>
            <ResponsiveContainer width="100%" height="85%">
              <PieChart>
                <Pie
                  data={distributionData}
                  cx="50%"
                  cy="50%"
                  labelLine={false}
                  outerRadius={80}
                  fill="#8884d8"
                  dataKey="value"
                  label={({ name, percent }) => `${name}: ${(percent ? percent * 100 : 0).toFixed(0)}%`}
                >
                  {distributionData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                  ))}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
          </div>
        </div>

        {/* 最近情绪记录 */}
        <div className="mt-6">
          <h3 className="text-md font-medium mb-3">Recent Emotions</h3>
          <div className="space-y-2 max-h-40 overflow-y-auto pr-2">
            {emotionData.map((item) => (
              <div key={item.id} className="p-3 bg-gray-50 rounded-md border border-gray-100 flex justify-between items-center">
                <div>
                  <div className="font-medium">{item.primary_emotion}</div>
                  <div className="text-sm text-gray-500">
                    {new Date(item.recorded_at).toLocaleString()}
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 rounded-full" style={{ backgroundColor: COLORS[Object.keys(emotionDistribution).indexOf(item.primary_emotion) % COLORS.length] }}></div>
                  <span className="text-sm font-medium">{item.emotion_intensity}/10</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </CardContent>
    </Card>
  )
}